<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Doit_m extends CI_Model {
	function __construct()
    {
        parent::__construct();
    }
	/********************************************
	* UPS交运
	**string 
	***********************************************/	
	public function getupsexpress()
	{
		if($this->config->item("upsexpressset")){
			$ups = stripslashes($this->config->item("upsexpressset"));
			$ups = unserialize($ups);
		}else{
			echo "未正常获得到UPS接口，请在订单相关设置中检查客户编码是否正确！";
			die;
		}
		$where  = "isexe = 0 AND orderType =2";
		$this->db->where($where);
		$total = $this->db->count_all_results('db_mabangorder');
		if($total==0)
		{
			echo "交运完成！";
			echo "<meta http-equiv=\"refresh\" content=\"1; url=/order/sfexpress/2 \">";
			die;
		}

		$rsdb = $this->db->get_one("SELECT * FROM db_mabangorder WHERE isexe = 0 AND orderType =2 ORDER BY id ASC");
		$orderID = $this->db->get_one("SELECT * FROM db_order_list WHERE order_sn ='".$rsdb["orderID"]."'");
		$goodslist = $this->db->get_where('db_order_sell',"order_id ='".$orderID["order_id"]."'")->result_array();
		$goodstr ='';
		$weight = 0;
		$weight  = $orderID["orderweight"];
		
		if($weight)
		{
			$weight = round($orderID["orderweight"] /1000,2);
		}else{
			foreach($goodslist as $key=>$rs)
			{
				if( $rs["goods_weight"]==0)
				{
					 $rs["goods_weight"] = 400;//400克
				}
				$weightst = ($rs["goods_weight"])/1000;
				$weight= $weight+$weightst;
				
			}
			$weight = round($weight,2);
		}
		
		$weight = 0.9;
	    $goodstr="<Package><PackagingType><Code>02</Code></PackagingType><Description>non-documents</Description><PackageWeight><UnitOfMeasurement><Code>KGS</Code></UnitOfMeasurement><Weight>$weight</Weight></PackageWeight></Package>";
		$invoicegoods="<Product><Description>costume sample</Description><Unit><Number>1</Number><Value>21.00</Value><UnitOfMeasurement><Code>PCS</Code></UnitOfMeasurement></Unit><CommodityCode>61032300</CommodityCode><PartNumber> </PartNumber><OriginCountryCode> CN</OriginCountryCode></Product>";
		$cust = trim($rsdb["customertel1"]);
		if($cust=='' || $cust =='null' || $cust=='none')
		{
			$rsdb["customertel1"]="0000000000";
		}
		
		
		if($rsdb["customerqq"] == "UK")
		{
			$rsdb["customerqq"]  = "GB";
		}
		$rsdb["customerzipcode"] = str_replace("-","",$rsdb["customerzipcode"]);//去掉邮编"-"
        $rsdb["customeraddress"]=str_replace("&","",$rsdb["customeraddress"]);//去掉&字符
        $rsdb["customerid"]=str_replace("&","",$rsdb["customerid"]);
        
		$strprovince = strlen($rsdb["customerprovince"]);
		if($strprovince>5)
		{
			$province = "";
		}else{
			$province =$rsdb["customerprovince"];
		}
		$straddress = strlen($rsdb["customeraddress"]);
		if($straddress<=35)
		{
			$address1 = $rsdb["customeraddress"];
		}else{
			$address1 = substr($rsdb["customeraddress"],0,35);
			$address2 = substr($rsdb["customeraddress"],35,70);
			$address3 = substr($rsdb["customeraddress"],70,105);
		}

		if(stripos($rsdb["customeraddress"],'PO Box')===0){
			$exememo = "收货地址PO Box位置不够具体";
			$postdata="";
			$postdata["isexe"] = 2;
			$postdata["exememo"] = $exememo;
			$postdata["mailinstime"] =time();
			$this->db->query($this->db->update_string('db_mabangorder', $postdata, 'id=' .$rsdb["id"]));
			$num = $num+1;
			$str = $rsdb["orderID"].$exememo;
			return array('num'=>$num,'str'=>$str);
		}
		
		$time = date("Ymd");
		$InvoiceXML = "<InvoiceLineTotal><CurrencyCode>RMB</CurrencyCode><MonetaryValue>$rsdb[goods_originask]</MonetaryValue></InvoiceLineTotal><ShipmentServiceOptions><InternationalForms><FormType>01</FormType>$invoicegoods<CurrencyCode>USD</CurrencyCode><ReasonForExport>SALE</ReasonForExport><InvoiceDate>$time</InvoiceDate>
		<Comments></Comments><DeclarationStatement>I hereby certify that the information on this invoice is true and correct and contents and value of this shipment is stated above.</DeclarationStatement></InternationalForms></ShipmentServiceOptions><SoldTo><CompanyName>$rsdb[customerid]</CompanyName><AttentionName>$rsdb[customerid]</AttentionName><PhoneNumber>$rsdb[customertel1]</PhoneNumber><Address><AddressLine1>$address1</AddressLine1><AddressLine2>$address2</AddressLine2><AddressLine3>$address3</AddressLine3><City>$rsdb[customercity]</City><StateProvinceCode>$province</StateProvinceCode><CountryCode>$rsdb[customerqq]</CountryCode><PostalCode>$rsdb[customerzipcode]</PostalCode></Address></SoldTo>";
		$url = $ups["upsurl1"];
		$cookie_jar = '';
		
		$xml ="<?xml version=\"1.0\"?><AccessRequest xml:lang=\"en-US\"><AccessLicenseNumber>$ups[accesskey]</AccessLicenseNumber><UserId>$ups[shippernumber]</UserId><Password>$ups[password]</Password></AccessRequest><?xml version=\"1.0\" encoding=\"utf-8\"?><ShipmentConfirmRequest xml:lang=\"en-US\"><Request><TransactionReference><CustomerContext>Customer Comment</CustomerContext><XpciVersion/></TransactionReference><RequestAction>ShipConfirm</RequestAction><RequestOption>validate</RequestOption></Request><Shipment><Shipper><Name>$ups[attentionname]</Name><AttentionName>$ups[attentionname]</AttentionName><CompanyDisplayableName>$ups[comname]</CompanyDisplayableName><ShipperNumber>$ups[shippernumber]</ShipperNumber><PhoneNumber>$ups[phonenumber]</PhoneNumber><Address> <AddressLine1>$ups[address]</AddressLine1><AddressLine2></AddressLine2> <AddressLine3></AddressLine3> <City>{$ups[city]}</City> <StateProvinceCode></StateProvinceCode> <PostalCode>{$ups[postcode]}</PostalCode> <CountryCode>{$ups[countrycode]}</CountryCode> </Address></Shipper><ShipTo> <CompanyName>$rsdb[customerid]</CompanyName><AttentionName>$rsdb[customerid]</AttentionName><PhoneNumber>$rsdb[customertel1]</PhoneNumber><EMailAddress></EMailAddress><Address><AddressLine1>$address1</AddressLine1><AddressLine2>$address2</AddressLine2><AddressLine3>$address3</AddressLine3><City>$rsdb[customercity]</City><StateProvinceCode>$province</StateProvinceCode><PostalCode>$rsdb[customerzipcode]</PostalCode><CountryCode>$rsdb[customerqq]</CountryCode></Address></ShipTo><PaymentInformation><Prepaid><BillShipper><AccountNumber>WY3000</AccountNumber></BillShipper></Prepaid></PaymentInformation><Service><Code>65</Code><Description>UPS Express</Description></Service><Description>non-documents</Description>$goodstr$InvoiceXML</Shipment><LabelSpecification><LabelPrintMethod><Code>GIF</Code><Description>GIF</Description></LabelPrintMethod><HTTPUserAgent>Mozilla/4.5</HTTPUserAgent><LabelImageFormat><Code>GIF</Code><Description>gif</Description></LabelImageFormat></LabelSpecification></ShipmentConfirmRequest>";
		
		$header = array('Content-Type:text/xml');
		$postdatast = $this->fun->curlfunc($url,$xml,$cookie_jar,$header);
		if($postdatast["err"]==201)
		{
			echo "交运返回错误：".$postdatast["txt"];
			die;
		}
		$vals = simplexml_load_string($postdatast);
		if($vals->Response->ResponseStatusCode==1)
		{
			//第二次握手
			$ShipmentDigest = $vals->ShipmentDigest;
			$url=$ups["upsurl2"];
			$xml="<?xml version=\"1.0\"?><AccessRequest xml:lang=\"en-US\"><AccessLicenseNumber>$ups[accesskey]</AccessLicenseNumber><UserId>$ups[shippernumber]</UserId><Password>$ups[password]</Password></AccessRequest><?xml version=\"1.0\" ?><ShipmentAcceptRequest><Request><TransactionReference><CustomerContext>guidlikesubstance</CustomerContext><XpciVersion>1.0001</XpciVersion></TransactionReference><RequestAction>ShipAccept</RequestAction></Request><ShipmentDigest>$ShipmentDigest</ShipmentDigest></ShipmentAcceptRequest>";
			$urldata = $this->fun->curlfunc($url,$xml,$cookie_jar,$header);
			$twovals = simplexml_load_string($urldata);
		
			
			if($twovals->Response->ResponseStatusCode==1)
			{
				$TotalCharges = $twovals->ShipmentCharges->TotalCharges->MonetaryValue;
				$exememo = '交运成功';
				$postdata["isexe"] = 1;
				$postdata["mailNo"] = $twovals->ShipmentResults->ShipmentIdentificationNumber[0];
				$postdata["originCode"] = 0;
				$postdata["destCode"] = 0;
				$postdata["printUrl"] = $twovals->ShipmentResults->PackageResults->LabelImage->HTMLImage;
				
				//保存图片到本地
				$dir = dirname(__FILE__) . "/../../uploads/upsexpress/".date("Ymd");
				!is_dir($dir) && @mkdir($dir, 0755, true);
				$Path = $dir. "/".$twovals->ShipmentResults->ShipmentIdentificationNumber."-order.gif";
				$content=$twovals->ShipmentResults->PackageResults->LabelImage->GraphicImage;
				if(file_put_contents($Path, base64_decode($content)))
				{
					$pathst = str_replace(dirname(__FILE__) . "/../../", '', $Path);
					$postdata["print_img"] = $pathst;
				}
				//保存发票信息
				$Path = $dir. "/".$twovals->ShipmentResults->ShipmentIdentificationNumber."-Invoice.pdf";
				$content=$twovals->ShipmentResults->Form->Image->GraphicImage;
				if(file_put_contents($Path, base64_decode($content)))
				{
					$pathpdf = str_replace(dirname(__FILE__) . "/../../", '', $Path);
					//下载好的pdf转成png
					$postdata["invoiceUrl"] =$pathpdf;
					//$rsInvoice = $this->fun->pdf2png($Path);
					//$postdata["invoice_img"] = $rsInvoice[0];
					
				}
				//将货号单号、物流公司更新到订单信息
				
				$update_order = "";
				$update_order["shipping_number"] = $postdata["mailNo"];	//运单号
				$update_order["shipping_time"] = time();				//交运时间
				$update_order["shipping_name"] = "UPS";
				$shipping =$this->fun->getdatabasesdetail("db_order_express"," AND name='UPS'");
				$update_order["shipping_id"] = $shipping["id"];
				//$update_order["shipping_expectfee"] = $twovals->ShipmentResults->ShipmentCharges->TotalCharges->MonetaryValue;
				$this->db->query($this->db->update_string('db_order_list', $update_order, "order_id='".$orderID["order_id"]."'"));
				
				//日志信息
				$imgdata="";
				$imgdata["goods_id"] = $orderID["order_id"];	//订单ID db_order_list
                $imgdata["updatetime"] = date("Y-m-d H:i:s");
                $imgdata["createUid"] = $_COOKIE['userid'];
                $imgdata["types"] = 3;
                $imgdata["content"] = '交运成功,交易ID='.$orderID['tradeid']."&nbsp;->&nbsp;UPS交运ID=".$postdata["mailNo"];
                $imgdata["createUser"] =$_COOKIE['username'];
                $this->db->insert('db_goods_log', $imgdata);


			}
		}else{
			$exememo = '交运失败';
			$postdata["isexe"] = 2;
			$exememo.=$vals->Response->Error->ErrorDescription;

			//交运失败，保存到订单备注
			$update_order = "";
			$update_order["remark"] = $orderID["remark"].$exememo;
			$this->db->query($this->db->update_string('db_order_list', $update_order, 'order_id="' .$orderID["order_id"].'"'));
		}
		$postdata["exememo"] = $exememo;
		$postdata["mailinstime"] =time();
		$this->db->query($this->db->update_string('db_mabangorder', $postdata, 'id=' .$rsdb["id"]));
		$num = $num+1;
		$str = $rsdb["orderID"].$exememo;
		return array('num'=>$num,'str'=>$str);
	}

	/********************************************
	* 顺丰交运
	**string 
	***********************************************/
	public function getsfexpress($page,$num)
	{
		
		
		$where  = "isexe = 0 AND orderType =1";
		$this->db->where($where);
		$total = $this->db->count_all_results('db_mabangorder');
		if($total==0)
		{
			echo "交运完成！";
			die;
		}
		$goodstr ='';
		$weight = 0;
		$rsdb = $this->db->get_one("SELECT * FROM db_mabangorder WHERE isexe = 0 AND orderType =1 ORDER BY id ASC");
		if($rsdb["isform"]==1)
		{
			$goodslist = $this->db->get_where('db_mabangsell',"orderid ='".trim($rsdb["orderID"])."'")->result_array();
			foreach($goodslist as $key=>$rs)
			{
				if( $rs["weight"]==0)
				{
					 $rs["weight"] = 400;//400克
				}
				$weightst = ($rs["ordernum"] * $rs["weight"])/1000;
				$weight= $weight+$weightst;
				$goodstr.= '<Cargo goods_code="'.$rs["productid"].'" product_record_no="'.$rs["productid"].'" name="woven polyester costume suit" count="1" unit="set" weight="'.$weightst.'" amount="21.99"  source_area="CN" />';
			}
		}else{
			$goodslist = $this->fun->getdatabaseslist("db_order_sell A left join db_order_list B on A.order_id = B.order_id"," AND B.order_sn='".trim($rsdb["orderID"])."'"," A.*");
			foreach($goodslist as $key=>$rs)
			{
				if( $rs["goods_weight"]==0)
				{
					 $rs["goods_weight"] = 400;//400克
				}
				$weightst = ($rs["goods_weight"])/1000;
				$weight= $weight+$weightst;
				$goodstr.= '<Cargo goods_code="'.$rs["goods_sn"].'" product_record_no="'.$rs["goods_sn"].'" name="woven polyester costume suit" count="1" unit="set" weight="'.$weightst.'" amount="21.99"  source_area="CN" />';
			}
		}
	
        $rsdb["customeraddress"]=str_replace("&","",$rsdb["customeraddress"]);//去掉&字符
        $rsdb["customerid"]=str_replace("&","",$rsdb["customerid"]);
		
		$cargo_total_weight = round($weight);
		$express_type = 207;	//国际标快-文件
		$custid = '0210028473';//月结卡
		$j_company = 'Shang Hai Jiang Qiao Branch CO.,LTD';	//寄件方公司名称
		$j_contact = 'Chao Zheng';//寄件方联系人
		$j_tel = '13818476032';	//寄件方联系电话
		$j_mobile ='13818476032';//手机
		$j_address='NO 288 ,Gao Chao Road ,Jia Ding District,Shang Hai';//地址
		$j_province='Shanghai';//省份
		$j_city = 'Shanghai';//城市
		$j_country = 'CN';
		$j_post_code = '201803';
		$d_company = $rsdb["customerid"];//到件方公司名
		$d_contact =$rsdb["customerid"];	//到件方联系人
		$d_tel = $rsdb["customertel1"]?$rsdb["customertel1"]:$rsdb["customertel2"];
		$d_mobile = $rsdb["customertel2"];
		$d_address = $rsdb["customeraddress"];
		$d_province =$rsdb["customerprovince"];
		$d_city =$rsdb["customercity"];
		$d_country = $rsdb["customerqq"];
		$d_post_code = $rsdb["customerzipcode"];
		
		if(strlen($d_post_code)>5){
			$d_post_code = substr($d_post_code,0,5);
		}

		$currency = 'USD';
		$parcel_quantity = 1;//包裹件数
		$tax = '';//买家税款
		
		$d_address=str_replace("í",'i',$d_address);
		
		if(stripos($rsdb["customeraddress"],'PO Box')===0){
			$exememo = "收货地址PO Box位置不够具体";
			$postdata["isexe"] = 2;
			$postdata["exememo"] = $exememo;
			$postdata["mailinstime"] =time();
			$this->db->query($this->db->update_string('db_mabangorder', $postdata, "id='".$rsdb["id"]."'"));
			$num = $num+1;
			$str = $rsdb["orderID"].$exememo;
			return array('num'=>$num,'str'=>$str);
		}


		$xml ='<?xml version="1.0" encoding="utf-8"?><Request service="apiOrderService" lang="zh-CN"><Head>OSMS_1305</Head><Body><Order orderid="'.$rsdb["orderID"].'" reference_no1="'.$rsdb["orderID"].'" express_type="'.$express_type.'" cargo_total_weight="'.$cargo_total_weight.'" custid="'.$custid.'" j_company="'.$j_company.'" j_contact="'.$j_contact.'" j_tel="'.$j_tel.'" j_mobile="'.$j_mobile.'" j_address="'.addslashes($j_address).'" j_province="'.$j_province.'" j_city="'.$j_city.'" j_county="" j_country="'.$j_country.'" j_post_code="'.$j_post_code.'" d_company="'.$d_company.'" d_contact="'.$d_contact.'" d_tel="'.$d_tel.'" d_mobile="'.$d_mobile.'" d_address="'.$d_address.'" d_province="'.$d_province.'" d_city="'.$d_city.'" d_county="" d_country="'.$d_country.'" d_post_code="'.$d_post_code.'" currency="'.$currency.'" parcel_quantity="'.$parcel_quantity.'" pay_method="1" printSize="1">'.$goodstr.'</Order></Body></Request>';

		//IBS系统为客户分配的密钥
		$checkword = 'eb9e2c5cddc94d5a';
		//对报文进行base64加密
		$data=base64_encode($xml);
		//1.拼接报文和密钥的
		//2.对拼接后的字符串进行MD5加密
		//3.再进行base64加密得到校验码
		$validateStr = base64_encode(md5(utf8_encode($xml).$checkword, false));
		//网络服务请求地址
		//$pmsLoginAction = 'http://osms.sf-express.com/osms/services/OrderWebService?wsdl';
		$pmsLoginAction = 'http://osms.sf-express.com/osms/services/OrderWebService?wsdl';
		$client = new SoapClient ($pmsLoginAction);
		$result=$client->sfexpressService(array('data'=>$data,'validateStr'=>$validateStr,'customerCode'=>'OSMS_1305'));//查询，返回的是一个结构体
		//print_r($result);
		$vals = simplexml_load_string($result->Return);
		//echo $vals->Head;
		//echo $vals->Body->OrderResponse->customerOrderNo;
		//echo $vals->Body->OrderResponse->originCode;
		//echo $vals->Body->OrderResponse->destCode;
		//echo $vals->Body->OrderResponse->printUrl;
		//echo $vals->Body->OrderResponse->invoiceUrl;
		$orderID = $this->db->get_one("SELECT * FROM db_order_list WHERE order_sn ='".$rsdb["orderID"]."'");
		if($vals)
		{
			if($vals->Head=='OK')
			{
				$exememo = '交运成功';
				$postdata["isexe"] = 1;
				$postdata["mailNo"] = $vals->Body->OrderResponse->mailNo;
				$postdata["originCode"] = $vals->Body->OrderResponse->originCode;
				$postdata["destCode"] = $vals->Body->OrderResponse->destCode;
				$postdata["printUrl"] = $vals->Body->OrderResponse->printUrl;
				$postdata["invoiceUrl"] = $vals->Body->OrderResponse->invoiceUrl;
				//保存远程PDF到本地，然后再转成png
				$dir = dirname(__FILE__) . "/../../uploads/sfexpress/".date("Ymd");
				!is_dir($dir) && @mkdir($dir, 0755, true);
				$Path = $dir. "/".$vals->Body->OrderResponse->customerOrderNo."-".time()."-order.pdf";
				$content=file_get_contents($vals->Body->OrderResponse->printUrl);//下载到内存
				file_put_contents($Path, $content);
				//下载好的pdf转成png
				$rsdbts = $this->fun->pdf2png($Path);
				$postdata["print_img"] = $rsdbts[0];

				
				$update_order = "";
				$update_order["shipping_number"] = $postdata["mailNo"];	//运单号
				$update_order["shipping_time"] = time();				//交运时间
				$update_order["shipping_name"] = "顺丰速运";
				$shipping =$this->fun->getdatabasesdetail("db_order_express"," AND name='顺丰速运'");
				$update_order["shipping_id"] = $shipping["id"];
				if($orderID["order_id"]){
					$this->db->query($this->db->update_string('db_order_list', $update_order, 'order_id=' .$orderID["order_id"]));
				}

				//日志信息

				$imgdata="";
				$imgdata["goods_id"] = $orderID["order_id"]?$orderID["order_id"]:0;	//订单ID db_order_list
                $imgdata["updatetime"] = date("Y-m-d H:i:s");
                $imgdata["createUid"] = $_COOKIE['userid'];
                $imgdata["types"] = 3;
                $imgdata["content"] = '交运成功,交易ID='.$orderID['tradeid']."&nbsp;->&nbsp;顺丰速运=".$postdata["mailNo"];
                $imgdata["createUser"] =$_COOKIE['username'];
                $this->db->insert('db_goods_log', $imgdata);


				$PathInvoice = $dir. "/".$vals->Body->OrderResponse->customerOrderNo."-".time()."-Invoice.pdf";
				$contentInvoice=file_get_contents($vals->Body->OrderResponse->invoiceUrl);//下载到内存
				file_put_contents($PathInvoice, $contentInvoice);
				//下载好的pdf转成png
				
				$rsInvoice = $this->fun->pdf2png($PathInvoice);
				$postdata["invoice_img"] = $rsInvoice[0];
				
			}else{
				$exememo = '交运失败';
				$postdata["isexe"] = 2;
				$exememo.=$vals->ERROR;

				//交运失败，保存到订单备注
				$update_order = "";
				$update_order["remark"] = $orderID["remark"].$exememo;
				$this->db->query($this->db->update_string('db_order_list', $update_order, 'order_id="' .$orderID["order_id"].'"'));
			}
			$postdata["exememo"] = $exememo;
			$postdata["mailinstime"] =time();
			$this->db->query($this->db->update_string('db_mabangorder', $postdata, "id='".$rsdb["id"]."'"));
			$num = $num+1;
			$str = $rsdb["orderID"].$exememo;

			return array('num'=>$num,'str'=>$str);
		}else{
			echo "未正常获得到顺丰接口，请检查客户编码是否正确！";
			die;
		}
	}
	
	
	/***********
	***	处理抓取远程图片，马帮或者内部系统抓取图片都使用这个功能
	*** images_url 原远程连接
	*** local_url  抓取后存放图片
	*** thumb_url  缩略图
	**************/
	function getMabangImages($url,$parent_goods='')
	{
		$file_path = pathinfo($url);
		
		if($parent_goods =="")
		{
			$parent_goods = $file_path["filename"];
		}
		
		$ch = curl_init(); 
		$timeout = 10; 
		curl_setopt ($ch, CURLOPT_URL, $url); 
		curl_setopt($ch, CURLOPT_HEADER, 1); 
		curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
		curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); 
		$contents = curl_exec($ch);
		
		if (preg_match("/404 Not Found/", $contents)){
			
			return false;
		}else{
			//抓取图片
			$Path1 =dirname(__FILE__)."/../../"; 
			$Path2 ="uploads/product/".date("Ymd");	//存储地址
			$dir = $Path1.$Path2;
			!is_dir($dir) && @mkdir($dir, 0755, true);
			$ors=rand(100, 999).substr(time(),-5).substr(microtime(),2,5);     //生成16位数字基本号
			$Path3= "/".$parent_goods."-".$ors."-product.".$file_path['extension'];
			$content=file_get_contents($url);//下载到内存
			$Path = $Path1.$Path2.$Path3;
		
			if(file_put_contents($Path, $content)>0)
			{
				$result_str["images_url"]= $url; 
				$result_str["local_url"]= $Path2.$Path3; 
				//存缩略图

				$upload_path_thumbnail = '/uploads/thumbnail/'.date("Ymd")."";
				$dirthumb = dirname(__FILE__) . "/../..".$upload_path_thumbnail;
				!is_dir($dirthumb) && @mkdir($dirthumb, 0755, true);
				if (file_exists($Path)) {
				$this->load->library('image_lib');
				$configimg['image_library'] = 'gd2';
				$configimg['source_image'] =$Path;
				$configimg['create_thumb'] = TRUE;
				$configimg['maintain_ratio'] = TRUE;
				$configimg['new_image'] =  $dirthumb."/". $file_path["filename"]."." . $file_path['extension'];
				$configimg['width']     = $this->config->item('resizeToWidth');
				$configimg['height']   = $this->config->item('resizeToHeight');
				$this->image_lib->initialize($configimg);
				if ( ! $this->image_lib->resize())
				{
					echo $this->image_lib->display_errors();
				}else{
					$this->image_lib->clear();
				}
				}
				$filesize = round(filesize($Path)/1024,2)."kb";//文件大小
				$result_str["filesize"] = $filesize;
				$result_str["filename"] = $file_path["filename"];
				$result_str["thumb_url"] = $upload_path_thumbnail."/". $file_path["filename"]."_thumb." .$file_path['extension'];
			}
			
			return $result_str;
		}
		
	}


	/*****自动同步新系统的定制SKU到工厂订单系统*********/
	public function autoinsertordertofactory()
	{
		$orderidstr = $_GET["orderid"];
		if($orderidstr){
			$orderidstr = array_unique(array_filter(explode(",",$orderidstr)));
			$orderidstr = implode("','",$orderidstr);
		}else{
			$orderidstr = "";
		}
		$endtime = date("Y-m-d H:i:s");
		$tbopertime = date("Y-m-d H:i:s",strtotime($endtime)-86000*7);	//只计算当前时间的前10个天的订单

		if($orderidstr)
		{
			$sql = "SELECT * FROM db_order_list where (order_status =2 or order_status =1 or order_status =3) AND order_sn in('".$orderidstr."')";
			
		}else{
			$sql = "SELECT * FROM db_order_list where (order_status =2 or order_status =1 or order_status =3) AND add_time>='" . strtotime($tbopertime) . "' and add_time<='" . strtotime($endtime) . "' and (order_source ='正常订单' or order_source ='手工创建')";
		}
		$query = $this->db->query($sql);
		$depts = $query->result_array();
		
	

		$factorycode = $this->fun->factorycode();
		
		foreach($depts as $key=>$rs)
		{
			$this->db->select('goods_sn,rec_id');
			$rsgoodslist = $this->db->get_where('db_order_sell',"order_id='".trim($rs["order_id"])."'")->result_array();
	
			foreach($rsgoodslist as $s=>$goods)
			{
				$goodsno = $goods["goods_sn"];
				if(is_numeric($goodsno) && preg_match('|^\d{8}$|',$goodsno))	//数字并且8位//判断是否是符合导订的要求 //8位SKU并且11 12开头
				{
					$goodscode  = substr($goodsno,0,2);
					if(in_array($goodscode,$factorycode))
					{
						$rsdb = $this->db->get_one("SELECT * FROM d_fmtask where orderid = '".trim($rs["order_sn"])."'");
						if(!$rsdb)
						{
							$postdata=array();
							$postdata["orderid"] = trim($rs["order_sn"]);
							$postdata["createtime"] = date("Y-m-d H:i:s");
							$postdata["finishtime"] = "0000-00-00 00:00:00";
							$postdata["flag"] = 0;
							$postdata["isform"] = 1;
							$postdata["descr"] = null;
							$this->db->insert('d_fmtask',$postdata);
						}
					}
				}
			}
		}
		if($orderidstr)
		{
			$sql = "UPDATE d_fmtask SET flag = 0 where orderid in('".$orderidstr."')";
			$this->db->query($sql);
		}
		$this->autoinsertfactoryPro($orderidstr);//执行保存的数据
	}

	
	public function autoinsertfactoryPro($orderidstr="")
	{
		/**************
			**  一个订单2个不一样的SKU，生成两个工厂订单　如：7050514473011，107000553
			**  一个订单2个一样的SKU,生成
			** 订单24100083613
		************/
		$err= 0;
		$orderlist = $this->db->get_where('d_fmtask',"flag = 0 AND isform =1")->result_array();
		foreach($orderlist as $key=>$rs)
		{
			$order_sn = trim($rs["orderid"]);
			$orderdata = $this->db->get_where('db_order_list',"order_sn='".$order_sn."'")->result_array();
			$tradeid = $orderdata[0]["tradeid"];
			$orderid = $orderdata[0]["order_id"];
			
				$ordersell = $this->db->get_where('db_order_sell',"order_id='".$orderid."'")->result_array();
				foreach($ordersell as $k=>$resell)
				{
					if(is_numeric($resell["goods_sn"]) && preg_match('|^\d{8}$|',$resell["goods_sn"]))	//数字并且8位//判断是否是符合导订的要求 //8位SKU并且11 12开头
					{
					
					}else{
						continue;
					}

					
					/*
					$rsdt = $this->db->get_one("select A.goods_sku,B.id,B.mabangorderid,backdealid from db_factory_sell A left JOIN db_factory_order B on A.orderId=B.id where B.backdealid='".$orderdata[0]["tradeid"]."' AND A.goods_sku='".$resell["goods_sn"]."'");
					if($rsdt)
					{
						if($orderidstr)
						{
							
						}else{
							continue;
						}
					}*/
					
					$rsdbshop = $this->db->get_one("SELECT * FROM d_shop WHERE id='". $orderdata[0]["shopid"]."'");
					$rsgoods = $this->db->get_where("db_goods","goods_sku='".$resell["goods_sn"]."'")->result_array();
					if(!$rsgoods[0]["goods_id"])	//没有这个SKU，提示错误，请先去提交SKU
					{
						$logerr = "";
						$logerr["orderID"]= $orderdata[0]["tradeid"];	//工厂订单错误
						$logerr["types"]= '工厂导入订单错误';	//工厂订单错误
						$logerr["errortext"]="新系统订单：".$orderdata[0]["order_sn"]." 商品编号：".$resell["goods_sn"]."不存在！导入工厂系统不成功！请先录入SKU信息！录入之后系统自动处理！";
						$logerr["touser"] = $rsdbshop["updateoper"]?$rsdbshop["updateoper"]:0;
						$logerr["sku"] = trim($resell["goods_sn"]);
						$rserr = $this->db->get_where("db_error_log","orderID='".$orderdata[0]["tradeid"]."' and types='工厂导入订单错误'")->result_array();
						if($rserr)
						{
							$logerr["isshow"]=0;
							$this->db->update('db_error_log',$logerr,"id='".$rserr[0]["id"]."'");
						}else{
							$logerr["instime"]=date("Y-m-d H:i:s");
							$this->db->insert('db_error_log',$logerr);
						}
						$err = 1;
						continue;
					}

					//如果是下架和停产商品，提醒销量不派单
					if($orderidstr==""){
						$rsgoodsdb = $this->fun->getdatabasesdetail("db_goods"," AND goods_sku = '".trim($resell["goods_sn"])."' AND g_sale_status in(4,7)");
						if($rsgoodsdb)
						{
							$rserror = $this->db->get_where("db_error_log","orderID='".$orderdata[0]["tradeid"]."' AND sku = '".trim($resell["goods_sn"])."' and types='工厂导入订单错误'")->result_array();
							if(!$rserror){
								$sale_remark = $resell['sale_remark']."<br><font color=red size=2>商品停产，订单导入工厂失败！请联系工厂</font>";					
								$this->db->update("db_order_sell",array('sale_remark'=>$sale_remark),"rec_id=".$resell['rec_id']);
								$logerr = "";
								$logerr["orderID"]= $orderdata[0]["tradeid"];	//工厂订单错误
								$logerr["types"]= '工厂导入订单错误';	//工厂订单错误
								$logerr["errortext"]="新系统订单：".$orderdata[0]["order_sn"]." 商品编号：".$resell["goods_sn"]." 商品停产，订单导入工厂失败！请联系工厂";
								$logerr["touser"] = $rsdbshop["updateoper"]?$rsdbshop["updateoper"]:0;
								$logerr["sku"] = trim($resell["goods_sn"]);
								$rserr = $this->db->get_where("db_error_log","orderID='".$orderdata[0]["tradeid"]."' and types='工厂导入订单错误'")->result_array();
								if($rserr)
								{
									$logerr["isshow"]=0;
									$this->db->update('db_error_log',$logerr,"id='".$rserr[0]["id"]."'");
								}else{
									$logerr["instime"]=date("Y-m-d H:i:s");
									$this->db->insert('db_error_log',$logerr);
								}
							}
								$err = 1;
								continue;
							
						}
					}





					$err  =0;
					$ORDERNUM = $resell["goods_number"];
					$rsdbfactorder = $this->db->get_where("db_factory","code ='".substr($resell["goods_sn"],0,2)."'")->result_array();
					
					for($i=1;$i<=$ORDERNUM;$i++)
					{
						if($ORDERNUM==1){
							$dealid = $orderdata[0]["tradeid"];
						}else{
						    $dealid = $orderdata[0]["tradeid"]."-".$i;
						}
						$this->db->trans_begin();
						$rsdbfact = $this->db->limit(1,0)->order_by('id','DESC')->select('orderId')->get("db_factory_order")->result_array();
						if($rsdbfact[0]["orderId"]<300000)
						{
							$fact_orderId = 300000;
						}else{
							$fact_orderId = $rsdbfact[0]["orderId"] +1;
						}
						$postdata = "";
						$postdata["orderId"]   = $fact_orderId;	//工厂订单号
						$postdata["orderTime"] = $rs["createtime"];	//下单时间
						$postdata["status"]	   = 1;	//订单状态
						$postdata["customerId"]= $orderdata[0]["customerid"];//顾客ID
						$postdata["customerName"]= $orderdata[0]["consignee"];//顾客姓名
						$postdata["country"]   = $orderdata[0]["country_cn"];//国家
						$postdata["city"]      = $orderdata[0]["city"];//城市
						$postdata["address"]   = addslashes($orderdata[0]["address"]);//地址
						$postdata["tel"]   = $orderdata[0]["tel"];//电话
						$postdata["email"]   = $orderdata[0]["email"];//邮箱
						$postdata["postal"]   = $orderdata[0]["zipcode"];//邮编 
						$postdata["shopId"]   = $orderdata[0]["shopname"];//店铺
						$postdata["factoryId"]   =  $rsdbfactorder[0]["id"];//工厂编号
						$postdata["platformId"]   = $rsdbshop["platfromname"];//平台
						$postdata["responsible"]   = $rsdbshop["updateoper"]?$rsdbshop["updateoper"]:0;//订单负责人
						$postdata["provice"]   = $orderdata[0]["province"];//省份
						$postdata["spcodeid"]   = 1;//公司外健 ？
						$postdata["updateflag"]   = 0;//没有派单
						$postdata["dealid"]     = $dealid;	//dealid
						$postdata["isform"]     = 1;	//1来源新系统0来源马帮
						$postdata["engCountry"]   = $orderdata[0]["country"];//英文国家
						$postdata["money"]   =  $orderdata[0]["goods_amount"];	//订单金额
						$postdata["mabangorderid"]   =  $orderdata[0]["order_sn"];//马帮OrderID
						$postdata["backdealid"]   =  trim($orderdata[0]["tradeid"]);//交易号
						//$postdata["moneyexpressask"]   = $orderdata[0]["MONEYEXPRESSASK"];//运费收入
						if($_COOKIE["username"]=='刘祥'){
							print_r($postdata);
						}
						$this->db->insert('db_factory_order', $postdata);
						$fastOrderid = $this->db->insert_id();
					
						$selldata="";
						$selldata["orderId"] = $fastOrderid;
						$selldata["goods_sku"] = $resell["goods_sn"];	//SKU
						$selldata["skuID"] = $rsgoods[0]["goods_id"];	//SKU
						$selldata["skuName"] = $rsgoods[0]["goods_name"];	//SKU
						$selldata["price"] =0;	//SKU
						$selldata["spcodeid"] =1;	//公司外健
						$selldata["orderNum"] =1;	//数量
						$this->db->insert('db_factory_sell', $selldata);
						
						/*******生成备注信息，如果超过1个SKU，每个订单备注中写上与哪个订单合发********/
						if($ORDERNUM>1){
							if($i == $ORDERNUM)	//最后一笔更新完成之后，计算需求填写的备注信息
							{
								$rsdbOrder = $this->db->get_one("SELECT GROUP_CONCAT(orderId) as needorder FROM `db_factory_order` WHERE 1 and backdealid='".trim($orderdata[0]["tradeid"])."'");//同属于一个交易订单
								if($rsdbOrder)
								{
									$memo = "以下订单一起发货：".$rsdbOrder["needorder"];
									$this->db->update("db_factory_order",array("descr"=>$memo),"backdealid='".trim($orderdata[0]["tradeid"])."'");
								}
							}
						}
						/*******生成备注信息，如果超过1个SKU，每个订单备注中写上与哪个订单合发完成********/

						if ($this->db->trans_status() === FALSE) {
							$this->db->trans_rollback();
						} else {
							$this->db->trans_commit();
						}
					}
				}
				
				if($err==1)
				{
					$this->db->update('d_fmtask',array("descr"=>date("Y-m-d H:i:s")."导入工厂系统失败,SKU不存在"),"orderid='".$orderdata[0]["order_sn"]."'");//订单处理完成，更新标识
				}else{
					$rserr = $this->db->get_where("db_error_log","orderID='".$orderdata[0]["order_sn"]."' and types='工厂导入订单错误'")->result_array();
					if($rserr)
					{
						$this->db->update('db_error_log',array("isshow"=>1),"id='".$rserr[0]["id"]."'");	//更新错误提示，不再提示
					}
					$this->db->update('d_fmtask',array("finishtime"=>date("Y-m-d H:i:s"),"flag"=>1,"descr"=>date("Y-m-d H:i:s")."成功导入工厂系统"),"orderid='". $orderdata[0]["order_sn"]."'");//订单处理完成，更新标识
					
					 if($orderidstr)
					 {
						$this->db->insert("db_factory_orderlog",array("orderId"=>$fastOrderid,"oper"=>$_COOKIE["userid"],"opername"=>$_COOKIE["username"],"operTime"=>date("Y-m-d H:i:s"),"descr"=>'手工派单成功 '.$str,"spcodeid"=>1));
					 }else{
						$this->db->insert("db_factory_orderlog",array("orderId"=>$fastOrderid,"oper"=>0,"opername"=>'System',"operTime"=>date("Y-m-d H:i:s"),"descr"=>'系统自动派单',"spcodeid"=>1));
					 }
				}
		}
		$this->autoInsertErrProudct();//自动处理没有导入到ERP的SKU系统
		echo "OK";
	}

	function AutoInsertImagesTo()
	{
		
		$res = $this->db->get_where("goodimages.goods"," isupdateImages = 0 AND del_flag= 0 and  length(number)=8 AND (locate(11,number)=1 or locate(12,number)=1 ) ")->result_array();
			//$res = $this->db->get_where("goodimages.goods"," isupdateImages = 0 AND del_flag= 0 and number='1358721' ")->result_array();
		if(count($res) ==0)
		{
			return;
		}
		
		foreach($res as $key=>$goods)
		{
			$isup= 0;
			$goods_sku = $goods['number'];
			$id = $goods["id"];
			$rsdb = $this->fun->getdatabasesdetail("db_goods"," AND goods_sku = '".trim($goods_sku)."'");
			if($rsdb){
				$rsImages = $this->fun->getdatabasesdetail('db_goods_images'," AND goods_id ='".$rsdb['goods_id']."'");
			
				if(!$rsImages)
				{

					//存储图片
					$Imageslist = "";
					$Imageslist =  $this->db->limit(3)->get_where("goodimages.goodpics"," type = 3 AND pid= '".$id."'")->result_array();
					if(count($Imageslist)>0){
						foreach($Imageslist as $res)
						{
							$picurl = "http://192.168.1.50/".$res['picurl'];
							if($res['picurl']){
								$isup=1;
								$Images = $this->getMabangImages($picurl,trim($goods_sku));							
								if($Images){
									$postImages = "";
									$postImages["goods_id"] = $rsdb['goods_id'];
									$postImages["images_type"]  = 1;
									$postImages["filesize"]  = $Images["filesize"];
									$postImages["images_url"]  = $Images["images_url"];
									$postImages["local_url"]  = $Images["local_url"];
									$postImages["thumb_url"]  =  $Images["thumb_url"];
									$postImages["filename"]  = $Images["filename"];
									$postImages["createUser"]  = $_COOKIE["username"]?$_COOKIE["username"]:'sys';
									$postImages["instime"]  = time();


									$this->db->insert('db_goods_images',$postImages);
								}
							}
						}
					}
				}

				//查询是否有子商品。如果有子商品需要同步子商品的图片信息
				$goodsImages = $this->db->get_where('db_goods_images',"goods_id='".$rsdb['goods_id']."'")->result_array();
				if($goodsImages)
				{
					$subgoodslist = $this->db->get_where('db_goods',"goods_id !='".$rsdb['goods_id']."' AND goods_parent_sku =  '".$rsdb['goods_sku']."'")->result_array();
					if(count($subgoodslist)>0)
					{
						foreach($subgoodslist as $key=>$rsGoods)
						{
							$rsImages = $this->fun->getdatabasesdetail('db_goods_images'," AND goods_id ='".$rsGoods['goods_id']."'");
							if(!$rsImages)
							{
									foreach($goodsImages as $k=>$r)
									{
										$Imgdata = "";
										$Imgdata["goods_id"] = $rsGoods['goods_id'];
										$Imgdata["images_type"] = 1;
										$Imgdata["images_url"] = $r["images_url"];
										$Imgdata["local_url"] = $r["local_url"];
										$Imgdata["thumb_url"] = $r["thumb_url"];
										$Imgdata["filename"] = $r["filename"];
										$Imgdata["filesize"] = $r["filesize"];
										$Imgdata["createUser"] = $r["createUser"];
										$Imgdata["instime"] = $r["instime"];
										$this->db->insert("db_goods_images",$Imgdata);
									}
								}
							}
						}
				}
				if($isup==1)$this->db->update('goodimages.goods',array("isupdateImages"=>1),"id='".$id."'");
			}
		}
		echo  "OK";
	}
	
	/*****自动更新全部的外采SKU商品图片******/
	function AutoInsertImagestoexternalBuyPro()
	{
		$res = $this->db->get_where("goodimages.goods"," isupdateImages = 0 AND del_flag= 0  ")->result_array();
		if(count($res)>0)
		{
			foreach($res as $key=>$rs)
			{
				if($this->fun->getfactorygoodsku($rs['number']) == false)
				{
					$this->AutoInsertImagesToexternalBuy($rs['number']);
				}
			}
		}
	}

	function AutoInsertImagesToexternalBuy($goodsSKU="")
	{
		
		$goods = $this->fun->getdatabasesdetail("goodimages.goods"," AND isupdateImages = 0 AND del_flag= 0 and  number = '".$goodsSKU."'");
		$isup= 0;
		$goods_sku = $goods['number'];
		$id = $goods["id"];
		$rsdb = $this->fun->getdatabasesdetail("db_goods"," AND goods_parent_sku = '".trim($goods_sku)."'");
		if($rsdb)
		{
				//存储图片
				$Imageslist = "";
				$Imageslist =  $this->db->limit(3)->get_where("goodimages.goodpics"," type = 3 AND pid= '".$id."'")->result_array();
				if(count($Imageslist)>0){
					foreach($Imageslist as $res)
					{
						$picurl = "http://192.168.1.50/".$res['picurl'];
						if($res['picurl']){
							$isup=1;
							$Images = $this->getMabangImages($picurl,trim($goods_sku));							
							if($Images){
								$postImages = "";
								$postImages["goods_id"] = $rsdb['goods_id'];
								$postImages["images_type"]  = 1;
								$postImages["filesize"]  = $Images["filesize"];
								$postImages["images_url"]  = $Images["images_url"];
								$postImages["local_url"]  = $Images["local_url"];
								$postImages["thumb_url"]  =  $Images["thumb_url"];
								$postImages["filename"]  = $Images["filename"];
								$postImages["createUser"]  = $_COOKIE["username"]?$_COOKIE["username"]:'sys';
								$postImages["instime"]  = time();

												

								$this->db->insert('db_goods_images',$postImages);
							}
						}
					}
				}
			
				//查询是否有子商品。如果有子商品需要同步子商品的图片信息
				$goodsImages = $this->db->get_where('db_goods_images',"goods_id='".$rsdb['goods_id']."'")->result_array();
				if($goodsImages)
				{
					$subgoodslist = $this->db->get_where('db_goods',"goods_id !='".$rsdb['goods_id']."' AND goods_parent_sku =  '".$goods_sku."'")->result_array();
					if(count($subgoodslist)>0)
					{
						foreach($subgoodslist as $key=>$rsGoods)
						{
							$rsImages = $this->fun->getdatabasesdetail('db_goods_images'," AND goods_id ='".$rsGoods['goods_id']."'");
							//if(!$rsImages)
							//{
									foreach($goodsImages as $k=>$r)
									{
										$Imgdata = "";
										$Imgdata["goods_id"] = $rsGoods['goods_id'];
										$Imgdata["images_type"] = 1;
										$Imgdata["images_url"] = $r["images_url"];
										$Imgdata["local_url"] = $r["local_url"];
										$Imgdata["thumb_url"] = $r["thumb_url"];
										$Imgdata["filename"] = $r["filename"];
										$Imgdata["filesize"] = $r["filesize"];
										$Imgdata["createUser"] = $r["createUser"];
										$Imgdata["instime"] = $r["instime"];
										$this->db->insert("db_goods_images",$Imgdata);
									}
								//}
							}
						}
				}
				if($isup==1)$this->db->update('goodimages.goods',array("isupdateImages"=>1),"id='".$id."'");
		}
		return true;
	}

	function autoInsertErrProudct($t=0)
	{
		if($t==1){	//指定需要导入的SKU信息
			$re = explode(",",$str);
			foreach($re as $key=>$rs)
			{
				$res[$key]["sku"] = $rs;
			}
			
		}else{
			$res = $this->db->get_where('db_error_log',"isshow =0")->result_array();
		}
		foreach($res as $key=>$rs)
		{
			$rsgoods = $this->db->get_where("db_goods","goods_sku='".trim($rs["sku"])."'")->result_array();
			if(count($rsgoods)==0)
			{
				$resskustr = $this->db->get_where('fshop.d_product',"productid = '".trim($rs["sku"])."'")->result_array();
				$ressku = $resskustr[0];
				if($ressku =='')
				{
					continue;
				}
				$postdata="";
				$bigclassID = 2;
				$secondclassID =4;
				$ThreeclassID = 0;
				if($ressku["factoryid"] ==12)	//工厂1
				{
					$supplier = 1;
				}elseif($ressku["factoryid"] ==10)
				{
					$supplier = 2;
				}else{
					$supplier = 3;
				}
				
				if($ressku["createdate"]){
					$OPERTIME= $ressku["createdate"];
				}else{
					$OPERTIME="2016-01-01 23:59:59";
				}
				$postdata['p_parent_sku']	= $ressku["productid"];
				$postdata['p_parent_name']	= $ressku["productname"];
				$postdata['p_en_goods_name']= $ressku["productnameen"];
				$postdata['p_yz']	= 0;
				$postdata['p_bigclassid']	= $bigclassID;
				$postdata['p_secondclassid']= $secondclassID;
				$postdata['p_threeclassid'] = $ThreeclassID;
				$postdata['p_goods_brand'] = null;
				$postdata['p_costprice']	= $ressku["factoryprice"]?$ressku["factoryprice"]:0;
				$postdata['p_procurement']  = 15;
				$postdata['p_inventory_day']= 15;
				$postdata['p_weight']		= 0;
				$postdata['p_sellprice']	= $ressku["sellprice"];
				$postdata['p_pd_length']	= 0;
				$postdata['p_pd_width']		= 0;
				$postdata['p_pd_height']	= 0;
				$postdata['p_pd_declare_value']= 60;
				$postdata['p_goodstypeID']	= 0;
				$postdata['p_sale_status'] =$ressku["status"]?$ressku["status"]:1;
				$postdata['p_updatetime']	=$OPERTIME;
				$postdata['p_intime']	=$OPERTIME;
				
				$postdata['p_createID']	=295;
				$postdata['p_createUser']='刘祥';
				$postdata['p_supplier']=$supplier;
				$postdata['p_checkman']	= '刘艺';
				$postdata['p_buyer']  = '刘艺';
				//$postdata['standard']	= $ressku["qualityinfo"];
				//$postdata['fabricinfo']	= $ressku["fabricinfo"]?$ressku["fabricinfo"]:0;
				$postdata['memo']  = $ressku["remark"];		
				$postdata['wages']  = $ressku["wages"]?$ressku["wages"]:0;	
				$this->db->trans_begin();
				
				$this->db->query($this->db->insert_string('db_goods_parent', $postdata));
				$parentID = $this->db->insert_id();
				
				/*********子商品**********/
					$postdata ="";
					$postdata["goods_parentID"] = $parentID;
					$parentList = $this->db->get_where('db_goods_parent','p_parent_id='.$parentID)->result_array();
					$postdata['goods_parent_sku']	= $parentList[0]["p_parent_sku"];
					$postdata['goods_name']	= $ressku["productname"];
					$postdata['yz']	= 0;
					$postdata['goods_sku']	= $ressku["productid"];
					$postdata['g_bigclassid']	= $parentList[0]['p_bigclassid'];
					$postdata['g_secondclassid']=$parentList[0]['p_secondclassid'];
					$postdata['g_threeclassid'] =$parentList[0]['p_threeclassid'];
					$postdata['en_goods_name']	=$ressku["productnameen"];
					$postdata['goods_brand']	=null;
					$postdata['g_costprice']	=$ressku["factoryprice"]?$ressku["factoryprice"]:0;
					$postdata['g_procurement']  = 15;
					$postdata['g_inventory_day']= 15;
					$postdata['g_weight']		=0;
					$postdata['g_sellprice']	=$ressku["sellprice"];
					$postdata['g_pd_length']	= 0;
					$postdata['g_pd_width']		=0;
					$postdata['g_pd_height']	= 0;
					$postdata['g_pd_declare_value']= 60;
					$postdata['g_goodstypeID']	= 0;
					$postdata['g_sale_status']  = $ressku["status"]?$ressku["status"]:1;
					$postdata['g_updatetime']	=$OPERTIME;
					$postdata['g_checkman']	= '刘艺';
					$postdata['g_buyer']  = '刘艺';
					$postdata['g_createID']		=295;
					$postdata['g_createUser']	='刘祥';
					//$postdata['standard']	=   $ressku["qualityinfo"];
					$postdata['memo']  = $ressku["remark"];	
					$postdata['g_supplier']=$supplier;
					$postdata['wages']  = $ressku["wages"]? $ressku["wages"]:0;	
					$postdata['fabricinfo']	= $ressku["fabricinfo"];
					$postdata['cognatelist']	= $ressku["childsku"];

					$this->db->query($this->db->insert_string('db_goods', $postdata));
					$goods_id = $this->db->insert_id();
					//更新日志
					$imgdata = "";
					$imgdata["goods_id"] = $goods_id;
					$imgdata["updatetime"] = date("Y-m-d H:i:s");
					$imgdata["createUid"] = 295;
					$imgdata["types"] = 1;
					$imgdata["content"] = '同步内部管理系统商品';
					$imgdata["createUser"] = '刘祥';
					$this->db->query($this->db->insert_string('db_goods_log', $imgdata));
					//更新默认仓库
					$where = array('goods_id' => $goods_id);
					$rsdbstock = $this->db->get_where('db_goods_stock',$where)->result_array();
					if(!$rsdbstock){
					$imgdata = "";
					$imgdata["goods_id"] = $goods_id;
					$imgdata["storage_name"] = '一号仓';
					$imgdata["storage_id"] = 1;
					$imgdata["stock"] =0;
					$imgdata["in_transit"] = 0;
					$imgdata["positions"] =$rs->LOCATION;
					$this->db->query($this->db->insert_string('db_goods_stock', $imgdata));
					}
					if ($this->db->trans_status() === FALSE)
					{
						$this->db->trans_rollback();
					}
					else
					{
						$this->db->trans_commit();
					}
			}
			
		}

	}

}

/* End of file Doit_m.php */